<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import _ from 'lodash';
import { api } from '@jzl/api';
import { ResizeObserver } from 'vue3-resize'
import {DFT_ICONS} from "@jzl/icons";
import { $jui } from '@jzl/utils';

// 定义props
const props = defineProps({
  mode: String,
  appId: Number,
  appCateShow: {
    type: Boolean,
    default: true
  }
});

// 定义emits
const emit = defineEmits(['select']);

// 路由
const route = useRoute();

// 响应式数据
const currentModuleId = ref(null);
const modules = ref([]);
const moduleWinName = ref('');
const moduleForm = ref({
  module_name: '',
  module_code: '',
  remark: ''
});
const moduleShow = ref(false);
const moduleSelect = ref({});
const moduleSelectWinShow = ref(false);
const projects = ref([]);
const form = ref({
  form_name: '',
  project_id: -1,
  app_id: null
});
const list = ref([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 50,
  count: 0
});
const tableHeight = ref(500);
const showCreate = ref(false);
const formInfo = ref(null);
const isView = ref(false);
const winName = ref('新增');
const isShowCopy = ref(false);
const copyForm = ref({});
const copyWinName = ref('');
const showViewWin = ref(false);
const viewsWinName = ref('');
const showActionWin = ref(false);
const actionWinName = ref('');
const showFlowCreate = ref(false);
const flowWinName = ref('');
const modFlowId = ref(null);
const flowForm = ref(null);
const settingWinName = ref('高级设置');
const showSettingCreate = ref(false);
const settingStepActive = ref(2);
const datasWinShow = ref(false);
const datasWinName = ref(false);
const currentForm = ref(null);
const pid = ref(null);
const tableContainer = ref(null);

// 过滤器转换为方法
const viewsLabel = (views) => {
  let labels = [];

  if (views && views.length) {
    for (let i = 0; i < views.length; i++) {
      let v = views[i];
      labels.push(`${v.view_name}(${v.form_view_code})`);
    }
  }
  return labels.join('<br/>');
};

// 方法定义
const init = async () => {
  pid.value = route.query.pid;

  let modulesData = await getApps();
  modules.value = modulesData;

  currentModuleId.value = props.appId;

  nextTick(() => {
    handleResize();
  });
};

const handleResize = () => {
  if (tableContainer.value) {
    let rect = tableContainer.value.getBoundingClientRect();
    let height = _.get(rect, 'height');

    if (height > 0) {
      tableHeight.value = height;
    }
  }
};

const _isGroup = (data) => {
  return !!_.get(data, 'group_id') && !_.get(data, 'content_id');
};

const isApp = (data) => {
  return _isGroup(data) && _.get(data, 'type') === 2;
};

const getApps = async () => {
  let ret = await api.admin.getAdminMenuTree();
  let apps = _.get(ret, 'groups', []);
  let notgroupsApps = [];
  let def = {
    group_name: '其他',
    subs: []
  };

  _.each(apps, (app) => {
    if (app && isApp(app)) {
      notgroupsApps.push(app);
    }
  });

  if (notgroupsApps && notgroupsApps.length) {
    def.subs = notgroupsApps;
    apps.push(def);
  }

  return apps;
};

const refresh = async () => {
  let data = await api.form.getFormList(
    _.assign(
      {
        page: pagination.value.current,
        pageSize: pagination.value.pageSize
      },
      form.value
    )
  );

  list.value = _.get(data, 'rows', []);
  pagination.value.count = _.get(data, 'count', 0);
};

const closeWin = (flag) => {
  showCreate.value = false;
  if (flag) {
    refresh();
  }
};

const handleShowCreate = () => {
  let app_id = currentModuleId.value;

  formInfo.value = null;
  if (app_id) {
    formInfo.value = { app_id };
  }
  showCreate.value = true;
  isView.value = false;
  winName.value = '创建表单';
};

const handleShowView = (it) => {
  formInfo.value = it;
  showCreate.value = true;
  isView.value = true;
  winName.value = `表单【${it.form_name}】`;
};

const handleShowEdit = (it, idx) => {
  showCreate.value = true;
  formInfo.value = it;
  isView.value = false;
  winName.value = `表单【${it.form_name}】`;
};

const _delete = async (id) => {
  let ret = await api.form.disableForm(id);

  if (ret && ret.form_id) {
    refresh();
  }
};

const handleDelete = (it) => {
  if (!it || !it.form_id) {
    return;
  }
  this.$confirm(`此操作将永久删除该表单【${it.form_name}】, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      _delete(it.form_id);
    })
    .catch(() => {});
};

const handleShowDatas = (it, idx) => {
  formInfo.value = it;
  datasWinShow.value = true;
  datasWinName.value = `预览表单【${it.form_name}】数据`;
};

const copy = async () => {
  let ret = await api.form.copyForm({
    orig_form_id: copyForm.value.form_id,
    form_name: copyForm.value.form_name,
    form_code: copyForm.value.form_code
  });

  if (ret) {
    isShowCopy.value = false;
    $jui.toast('恭喜您，表单复制成功');
    refresh();
  }
};

const handleShowViews = (it, idx) => {
  showViewWin.value = true;
  formInfo.value = it;
  viewsWinName.value = `【${it.form_name}】的视图`;
};

const handleCloseViewWin = (flag) => {
  showViewWin.value = false;
  formInfo.value = null;
  refresh();
};

const handleShowSetting = (it, idx, stepActive) => {
  formInfo.value = it;
  showActionWin.value = true;
  settingWinName.value = `【${it.form_name}】高级设置`;
  showSettingCreate.value = true;
  settingStepActive.value = stepActive;
};

const handleSelect = (it, idx) => {
  emit('select', it);
};

const handleShowFlowEditWin = (it) => {
  flowForm.value = it;
  showFlowCreate.value = true;
};

const handleShowFlowAddWin = (it) => {
  flowForm.value = it;
  showFlowCreate.value = true;
};

const handleCloseFlowWin = () => {
  showFlowCreate.value = false;
  refresh();
};

const handleCloseSettingWin = () => {
  showSettingCreate.value = false;
};

const handleAddModule = () => {
  // 空实现，保持与原代码一致
};

const handleCreateModule = async () => {
  let ret = await api.form.createFormModule(moduleForm.value);

  if (ret) {
    init();
    currentModuleId.value = _.get(ret, 'group_id');
    handleHideModuleWin();
  }
};

const handleHideModuleWin = () => {
  moduleShow.value = false;
};

const handleShowModuleSelectWin = (f) => {
  moduleSelectWinShow.value = true;
  currentForm.value = f;
  moduleSelect.value = {};
};

const handleHideModuleSelectWin = () => {
  moduleSelectWinShow.value = false;
};

const handleModuleSelectOne = (m) => {
  moduleSelect.value = m;
};

const handleModuleChange = async () => {
  if (!currentForm.value || !moduleSelect.value) {
    return;
  }
  let ret = await api.form.updateFormSimple(currentForm.value.form_id, {
    app_id: moduleSelect.value.group_id
  });

  if (ret) {
    $jui.toast('变更成功！');
    refresh();
    handleHideModuleSelectWin();
  }
};

// 生命周期
onMounted(() => {
  init();
  refresh();
});

// 监听器
watch(currentModuleId, (val) => {
  form.value.app_id = val;
  pagination.value.current = 1;
  refresh();
});

watch(
  () => props.appId,
  (val) => {
    currentModuleId.value = val;
  }
);
</script>

<template>
  <div class="portal-detail-container form-list-wrap">
    <AppCate
      v-model="currentModuleId"
      v-if="appCateShow"
      :show-plat="false"
      :show-project="false"
      class="app-cate-menu"
    />
    <div class="mb-info" style="background: none;">
      <div
        class="query-search-thin mb-0"
      >
        <el-form
          :inline="true"
          @submit.prevent
        >
          <el-form-item>
            <el-input
              placeholder="搜索表单名称"
              v-model="form.form_name"
              class="input-with-select"
              clearable
              @clear="refresh"
              @keyup.enter="refresh"
            >
              <template #append>
                <el-button
                  @click="refresh()"
                >
                  <template #icon>
                    <JIcon :icon="DFT_ICONS.search" />
                  </template>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          @click="handleShowCreate()"
        >
          <template #icon>
            <JIcon :icon="DFT_ICONS.add" />
          </template>新增
        </el-button>
      </div>
      <div
        class="flex-1 h-full mt-2 overflow-hidden"
        ref="tableContainer"
      >
        <el-table
          :data="list"
          class="m-table"
          border
          size="small"
          height="100%"
        >
          <el-table-column
            prop="form_name"
            label="表单名"
          >
            <template #default="scope">
              <a
                href="javascript:void(0)"
                @click="handleShowDatas(scope.row, scope.$index)"
              >{{scope.row.form_name }}</a>
              <JIcon
                :icon="DFT_ICONS.flow"
                class="form-flow-tag"
                v-if="scope.row.use_type === 'WORKFLOW'"
                v-tippy
                content="流程类表单"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="form_name"
            width="120"
            label="所属应用"
          >
            <template #default="scope">
              <div
                class="i-btn"
                v-tippy
                :content="(scope.row.app && scope.row.app.group_name) || '未分组'"
                @click="handleShowModuleSelectWin(scope.row, scope.$index)"
              >
                <JIcon :icon="DFT_ICONS.edit" v-if="!scope.row.app || !scope.row.app.group_name" />
                {{ (scope.row.app && scope.row.app.group_name) || '未分组' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="form_code"
            label="表单编码"
          />
          <el-table-column
            prop="form.user_type"
            label="流程"
            align="center"
            width="60"
          >
            <template #default="scope">
              <template v-if="scope.row.use_type === 'WORKFLOW'">
                <div
                  v-if="scope.row.flow_id"
                  class="i-btn"
                  v-tippy
                  :content="scope.row.flow.flow_name"
                  @click="handleShowFlowEditWin(scope.row, scope.$index)"
                >
                  <JIcon :icon="DFT_ICONS.edit" />
                </div>
                <div
                  v-else
                  class="i-btn text-center"
                  @click="handleShowFlowAddWin(scope.row, scope.$index)"
                >
                  <JIcon :icon="DFT_ICONS.add" />
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="视图"
            align="center"
            width="60"
          >
            <template #default="scope">
              <div
                v-if="scope.row.views.length"
                class="i-tag"
                v-tippy
                :content="viewsLabel(scope.row.views)"
                @click="handleShowViews(scope.row, scope.$index)"
              >
                {{ scope.row.views.length }}
              </div>
              <div v-else class="i-btn" @click="handleShowViews(scope.row, scope.$index)">
                <JIcon :icon="DFT_ICONS.add" />
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="310" align="center" class-name="col-action">
            <template #default="scope">
              <template v-if="mode == 'select'">
                <el-button
                  size="small"
                  type="text"
                  @click="handleSelect(scope.row, scope.$index)"
                >选择</el-button>
              </template>
              <template v-else>
                <el-button
                  size="small"
                  type="text"
                  @click="handleShowView(scope.row, scope.$index)"
                >修改</el-button>
                <el-button
                  size="small"
                  type="text"
                  @click="handleShowSetting(scope.row, scope.$index, 3)"
                >低码开发</el-button>
                <el-button
                  size="small"
                  type="text"
                  @click="handleShowSetting(scope.row, scope.$index, 1)"
                >功能按钮</el-button>
                <el-button
                  size="small"
                  type="text"
                  @click="handleShowSetting(scope.row, scope.$index, 2)"
                >智能同步</el-button>
                <el-button
                  size="small"
                  type="text"
                  @click="handleDelete(scope.row, scope.$index)"
                >删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>

        <ResizeObserver @notify="handleResize" />
      </div>
      <el-pagination
        @size-change="refresh"
        @current-change="refresh"
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.count"
        class="mt-2"
      />
    </div>

    <el-dialog
      :title="winName"
      v-model="showCreate"
      fullscreen
      class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <FormCreate
        v-if="showCreate"
        @close="closeWin"
        :form-info="formInfo"
        :show="showCreate"
        use-type="WEB"
        :is-show-form="true"
      />
    </el-dialog>

    <el-dialog
      :title="datasWinName"
      v-model="datasWinShow"
      fullscreen
      class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <datas
        v-if="formInfo"
        :form-id="formInfo.form_id"
        style="min-height: 300px; padding: 10px"
      ></datas>
    </el-dialog>

    <el-dialog
      :title="viewsWinName"
      v-model="showViewWin"
      fullscreen
      class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <form-views
        v-if="showViewWin && formInfo"
        @close="handleCloseViewWin"
        :form-id="formInfo.form_id"
        :show="showViewWin"
      ></form-views>
    </el-dialog>

    <el-dialog
      :title="copyWinName"
      v-model="isShowCopy"
      width="600px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form size="small" label-width="100px">
        <el-form-item label="新表单名称">
          <el-input v-model="copyForm.form_name"></el-input>
        </el-form-item>
        <el-form-item label="新表单编码">
          <el-input v-model="copyForm.form_code"></el-input>
        </el-form-item>
      </el-form>
      <div class="text-center">
        <el-button type="primary" @click="copy()"> 提交 </el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="flowWinName"
      v-model="showFlowCreate"
      fullscreen
      class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <flow-create
        @close="handleCloseFlowWin"
        v-if="showFlowCreate"
        :show="showFlowCreate"
        :flow-id="flowForm && flowForm.flow_id"
        :rel-form-id="flowForm && flowForm.form_id"
        :is-view="isView"
      ></flow-create>
    </el-dialog>

    <el-dialog
      :title="settingWinName"
      v-model="showSettingCreate"
      fullscreen
      class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <form-setting
        @close="handleCloseSettingWin"
        v-if="showSettingCreate"
        :show="showSettingCreate"
        :step-active="settingStepActive"
        :form-id="formInfo && formInfo.form_id"
        :is-view="isView"
      ></form-setting>
    </el-dialog>

    <el-dialog
      :title="moduleWinName"
      v-model="moduleShow"
      width="600px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form size="small" label-width="100px">
        <el-form-item label="模块名称" required>
          <el-input v-model="moduleForm.module_name" placeholder="建议长度不超过5个字符"></el-input>
        </el-form-item>
        <el-form-item label="模块唯一码" required>
          <el-input
            v-model="moduleForm.module_code"
            placeholder="模块唯一码，也是定制脚本文件目录。如：ndkh"
          ></el-input>
        </el-form-item>
        <el-form-item label="模块描述">
          <el-input v-model="moduleForm.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div class="text-center">
        <el-button type="primary" @click="handleCreateModule()"> 提交 </el-button>
        <el-button @click="handleHideModuleWin()"> 关闭 </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择所属应用"
      v-model="moduleSelectWinShow"
      width="800px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-alert
        show-icon
        type="warning"
        :closable="false"
        style="margin-bottom: 20px"
        title="请勿随意变更所属应用，所属应用分组也是开发者定制脚本的文件目录，变更会导致脚本失效！"
      >
      </el-alert>
      <div>
        <div class="group" v-for="g in modules" :key="g.group_name">
          <h5
            v-text="g.group_name"
            style="font-size: 12px; line-height: 1.2; margin: 5px 0; font-weight: bold"
          />
          <el-row :gutter="20">
            <el-col span="8" v-for="m in g.subs" :key="m.group_id">
              <el-button
                @click="handleModuleSelectOne(m)"
                :type="m.group_id === moduleSelect.group_id ? 'primary' : ''"
                class="w-full mb-2"
              >
                <template #icon v-if="m.group_id === moduleSelect.group_id">
                  <JIcon :icon="DFT_ICONS.check" />
                </template>
                {{ m.group_name }}</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="text-center">
        <el-button type="primary" @click="handleModuleChange()"> 提交 </el-button>
        <el-button @click="handleHideModuleSelectWin()"> 关闭 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.el-button [class*='el-icon-'] + span {
  margin-left: 2px;
}

.el-tag {
  margin-right: 5px;

  &:last-child {
    margin-right: 0px;
  }
}
.i-btn {
  color: #409eff;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  cursor: pointer;
}
.i-tag {
  background: #90aeff;
  color: #fff;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  line-height: 20px;
  margin: 0 auto;
  cursor: pointer;

  &:hover {
    background: #3a8ee6;
  }
}
</style>
